<template>
  <div>
  <a-card title="主机指标" :bordered="true" style="width: 100%" class="metric-vms">
    <div class="metric-vms-content">
      <div ref="cpuChart" :style="{ width: '50%', height: '300px' }"></div>
      <div ref="memChart" :style="{ width: '50%', height: '300px' }"></div>
    </div>
  </a-card>
  <a-card title="CPU详细使用率" :bordered="true" style="width: 100%" class="core-usage-vms">
    <div class="core-usage-vms-content">
      <CoreUsage v-for="(hostData, index) in coreUsageData" :host-data="hostData" :key="index"></CoreUsage>
    </div>
  </a-card>
  </div>
</template>

<script setup>
import CoreUsage from '@/components/CoreUsage.vue'

import * as echarts from 'echarts';
import { ref, onMounted, watch, nextTick, toRefs } from 'vue';
import { defineProps } from 'vue';

const props = defineProps({
  lastData: {
    type: Array,
    required: true
  },
  cpuUsage: {
    type: Array,
    required: true
  }
});

const { lastData,cpuUsage } = toRefs(props);
const groupData = ref({});
const coreUsageData = ref([]);
const cpuChart = ref(null);
const memChart = ref(null);
let cpuChartInstance = null;
let memChartInstance = null;

const initCharts = () => {
  cpuChartInstance = echarts.init(cpuChart.value);
  memChartInstance = echarts.init(memChart.value);
  updateCharts();
};


const updateCharts = () => {
  const cpuData = groupData.value.total_cpu_usage || [];
  const memData = groupData.value.mem_used_percent || [];

  const cpuHosts = cpuData.map(item => item.Host);
  const cpuValues = cpuData.map(item => parseFloat(item.Value));

  const memHosts = memData.map(item => item.Host);
  const memValues = memData.map(item => parseFloat(item.Value));

  const cpuOption = {
    title: {
      text: 'CPU整体使用率',
      textStyle: {
        fontSize: 18,
        fontWeight: 500
      }
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: cpuHosts
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} %'
      }
    },
    series: [
      {
        name: 'CPU使用',
        type: 'bar',
        data: cpuValues.map(value => ({ value, itemStyle: { color: '#5470C6' } })),
        label: {
          show: true,
          position: 'top',  // 标签位置
          formatter: '{c} %',  // 显示数值及百分号
          fontSize: 12,        // 字体大小
          fontWeight: 'bold'   // 字体加粗
        }
      }
    ]
  };

  const memOption = {
    title: {
      text: '内存整体使用率',
      textStyle: {
        fontSize: 18,
        fontWeight: 500
      }
    },
    tooltip: {},
    xAxis: {
      type: 'category',
      data: memHosts
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '{value} %'
      }
    },
    series: [
      {
        name: '内存使用',
        type: 'bar',
        data: memValues.map(value => ({ value, itemStyle: { color: '#91CC75' } })),
        label: {
          show: true,
          position: 'top',  // 标签位置
          formatter: '{c} %',  // 显示数值及百分号
          fontSize: 12,        // 字体大小
          fontWeight: 'bold'   // 字体加粗
        }
      }
    ]
  };

  cpuChartInstance.setOption(cpuOption);
  memChartInstance.setOption(memOption);
};

function groupByMetric(data) {
  let groupedResult = {
    total_cpu_usage: [],
    mem_used_percent: []
  };
  data.forEach(item => {
    groupedResult.total_cpu_usage.push({
      Host: item.hostName,
      Value: item.totalCPUUsage.toFixed(1)
    });
    groupedResult.mem_used_percent.push({
      Host: item.hostName,
      Value: item.memUsedPercent.toFixed(1)
    });
  });
  return groupedResult;
}

onMounted(() => {
  nextTick(() => {
    initCharts();
  });
});

watch([() => lastData.value, () => cpuUsage.value], ([newLastData, newCpuUsage]) => {

  //1. newLastData
  let newLastDataArray = newLastData.map(item => {
    return { ...item };
  });
  console.log("newLastDataArray", newLastDataArray)
  groupData.value = groupByMetric(newLastDataArray);
  let newCpuUsageArray = newCpuUsage.map(item => {
    return { ...item };
  });
  console.log("newCpuUsageArray", newCpuUsageArray)
  //2.newCpuUsage
  const groupedData = newCpuUsageArray.reduce((acc, item) => {
    if (!acc[item.hostName]) {
      acc[item.hostName] = {
        Host: item.hostName,
        core_usages: []
      };
    }
    acc[item.hostName].core_usages[item.cpuId] = item.usagePercent.toFixed(2); // 按 cpuId 存储 usagePercent
    return acc;
  }, {});
  // 转换为二维数组
  const transformedData = Object.values(groupedData);
  // 赋值给 coreUsageData.value
  coreUsageData.value = transformedData;

  if (cpuChartInstance && memChartInstance) {
    updateCharts();
  }
});

</script>

<style lang="less">
.metric-vms {
  .ant-card-head-title {
    font-size: 1rem;
    font-weight: 600 !important;
  }
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  .metric-vms-content {
    display: flex;
    flex-direction: row;

    > div {
      flex: 1;
    }
  }

  .echarts-title {
    font-size: 1rem;
    font-weight: 500;
  }
}

.core-usage-vms {
  .ant-card-head-title {
    font-size: 1rem;
    font-weight: 600 !important;
  }
  display: flex;
  flex-direction: column;
  margin-top: 20px;
  .core-usage-vms-content {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start; 

    > div {
      flex: 0 0 25%; 
      max-width: 25%; 
      box-sizing: border-box;
    }
  }
}
</style>
